#include "netdisk3.h"

int login(int netfd, char* name, MYSQL* mysql){
    int uerror = 2;
    int perror1 = 1;
    int right = 0;

    char username[128] = {0};
    char passwd[4096] = {0};
    char salt[10] = {0};

    char sql[4096] = {0};

    int times = 4;
    int name_length = 0;
    int passwd_length = 0;
    
    while(1){
        bzero(username, sizeof(username));
        bzero(passwd, sizeof(passwd));
        bzero(sql, sizeof(sql));

        if(times == 0){
            return -1;
        }
        
        recvn(netfd, &name_length, sizeof(int));
        recvn(netfd, username, name_length);

        recvn(netfd, &passwd_length, sizeof(int));
        recvn(netfd, passwd, passwd_length);

        // 验证用户是否存在
        sprintf(sql, "select * from info where name = '%s';", username);
        int ret = mysql_query(mysql, sql);
        MYSQL_QUERY_CHECK(ret, mysql);

        MYSQL_RES* result = mysql_store_result(mysql);
        MYSQL_ROW row = mysql_fetch_row(result);
        // 如果没找到改用户，则发送错误消息
        if(row == NULL){
            send(netfd, &uerror, sizeof(int), 0);
            continue;
        }

        memcpy(salt, row[2], strlen(row[2]));
        // 得到盐值后计算密码
        char* crypasswd = crypt(passwd, salt);

        if(strcmp(crypasswd, row[3]) == 0){
            send(netfd, &right, sizeof(int), 0);
            memcpy(name, username, strlen(username));
            
            mysql_free_result(result);
            return 0;
        }else{
            // 密码错误
            send(netfd, &perror1, sizeof(int), 0);
            --times;

            mysql_free_result(result);
            continue;
        }
    }
    return -1;
}

int getCurrFolder(char* username, MYSQL* mysql){
    char sql[4096] = {0};
    sprintf(sql, "select * from virtual_file where name = '/'"
            "and user = '%s' and tomb = 0;", username);

    int Mret = mysql_query(mysql, sql);
    MYSQL_QUERY_CHECK(Mret, mysql);

    MYSQL_RES* result = mysql_store_result(mysql);
    MYSQL_ROW row = mysql_fetch_row(result);
    int retVal;
    if(row == NULL){
        mysql_free_result(result);
        return -1;
    }else{
        retVal = atoi(row[0]);
        mysql_free_result(result);
        return retVal;
    }
}

